from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.decorators import csrf
from django.contrib import auth
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from User.models import *
from WordBook.models import WordBook as WB
from time import gmtime, strftime
from django.db import connections
from django.core.paginator import Paginator, Page, PageNotAnInteger, EmptyPage
# Create your views here.


def home(request):
    return render(request, 'home.html')


def login(request):
    if request.method == "POST":
        origin = request.GET.get('next')  # 用来记录是否从某个页面跳转而来 str类型 没有则为None类型
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")
        # 验证成功，返回user对象，否则返回None
        user = auth.authenticate(username=user, password=pwd)
        if user:
            auth.login(request, user)  # session写操作
            if origin:  # 如果从其他页面跳转过来，就跳转回去
                return redirect(origin)
            return redirect("/user/home/")
        else:
            return render(request, 'login.html', {'error': "用户名或密码错误！！！"})
    return render(request, "login.html")


def logout(request):
    auth.logout(request)  # 让用户注销
    return redirect("/user/home/")


def register(request):
    if request.method == 'POST':
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        # 如果用户名已经存在，就返回错误信息
        if User.objects.filter(username=user):
            return render(request, 'register.html', {'error': "用户名已经存在！！！"})
        else:
            # 创建用户
            user_info = User.objects.create_user(username=user, password=pwd)
            # 同时创建个人信息，初始值为空
            user = User.objects.filter(username=user)[0]
            user_inf = UserInformation(user_id=user)
            user_inf.save()
            return redirect("/user/home/")
    return render(request, 'register.html')


@login_required
def mydetail(request):
    pk = request.user.pk  # 获取当前登录用户的id
    user_detail = UserInformation.objects.filter(
        user_id=pk)[0]  # 根据id在个人信息中找到用户信息，并展示出来
    return render(request, 'mydetail.html', {'user_detail': user_detail})


@login_required
def adddetail(request):
    pk = request.user.pk  # 获取当前登录用户的id
    user_detail = UserInformation.objects.filter(
        user_id=pk)[0]  # 根据id在个人信息中找到用户信息
    if request.method == 'POST':
        user_detail.user_email = request.POST.get('user_email')
        user_detail.user_sex = request.POST.get('user_sex')
        if request.POST.get('user_age').isdigit():  # 数据库建模限制这里必须是整数
            user_detail.user_age = request.POST.get('user_age')
        if request.POST.get('user_birthday'):  # 用户没有提交生日信息的话会返回空字符串，保存到数据库时会报错
            user_detail.user_birthday = request.POST.get('user_birthday')
        user_detail.user_area = request.POST.get('user_area')
        if request.POST.get('user_qq').isdigit():
            user_detail.user_qq = request.POST.get('user_qq')
        if request.POST.get('user_telephone').isdigit():
            user_detail.user_telephone = request.POST.get('user_telephone')
        user_detail.user_school = request.POST.get('user_school')
        user_detail.user_signature = request.POST.get('user_signature')
        user_detail.save()
        return redirect('/user/mydetail/')
    return render(request, 'adddetail.html', {'user_detail': user_detail})


@login_required
def mybook(request):
    # 获取当前用户
    pk = request.user.pk
    user = User.objects.filter(pk=pk)[0]
    # 查询当前用户词本
    books_list = UserBooks.objects.filter(master=user)
    return render(request, 'mybook.html', {'books_list': books_list})


@login_required
def add_mybook(request):
    # 获取当前用户
    pk = request.user.pk
    user = User.objects.filter(pk=pk)[0]
    if request.method == 'POST':
        # 获取当前时间，并格式化为年-月-日格式
        pub_date = strftime('%Y-%m-%d', gmtime())
        title = request.POST.get('title')
        is_public = request.POST.get('is_public')
        password = request.POST.get('password')
        need_pwd = request.POST.get('need_pwd')
        # 判断是否有未填写的内容
        try:
            if title and password:
                book = UserBooks(title=title, pub_date=pub_date,
                                 is_public=is_public, password=password, need_pwd=need_pwd)
                book.save()
                book.master.add(user)
                # 如果这个词本是公开展示的话，则增添到公共词本里面
                if is_public:
                    # 这里直接拷贝一份，防止多个用户修改一个词本的现象。在拷贝之时，通过pk使它们具有关系
                    # 应该保证所有代码中，只有创建单词本，才能在公共词本中添加
                    book1 = WB(pk=book.pk, title=title, pub_date=pub_date, is_public=is_public,
                               password=password, need_pwd=need_pwd, master=user)  # master保存是为了记录当前单词本的用户
                    book1.save()
                return redirect('/user/mybook/')
        except:
            return render(request, 'add_mybook.html', {'error': "有部分信息未填写！！！"})
    return render(request, 'add_mybook.html')


@login_required
def del_mybook(request):
    # 查找到当前用户
    pk = request.user.pk
    user = User.objects.filter(pk=pk)[0]
    # get到当前所需要编辑的单词本的id
    pk = request.GET.get('pk')
    # 删除单词本
    UserBooks.objects.get(pk=pk, master=user).delete()
    # 这里采用filter，判断当这个单词本有主的时候才能在公共库中删除
    WB.objects.filter(pk=pk, master=user).delete()
    return redirect('/user/mybook/')


@login_required
def edit_mybook(request):
    # 获取当前用户
    pk = request.user.pk
    user = User.objects.filter(pk=pk)[0]
    # 获取当前图书
    pk = request.GET.get('pk')
    book = UserBooks.objects.get(pk=pk, master=user)
    # 判断是否为POST请求
    if request.method == 'POST':
        title = request.POST.get('title')
        password = request.POST.get('password')
        # 判断title 和 password 是否非空
        if title and password:
            # 保存信息
            book.title = title
            book.is_public = request.POST.get('is_public')
            book.password = password
            book.need_pwd = request.POST.get('need_pwd')
            book.save()
            book.master.add(user)
            # 查询并判断在公共库中是否存在该单词本,并且只有当单词本的主人是当前用户时才允许被用户修改
            book1 = WB.objects.filter(pk=pk, master=user)
            if book1:
                book1 = book1[0]
                book = UserBooks.objects.get(pk=pk, master=user)
                book1.title = title
                book1.is_public = book.is_public
                book1.password = password
                book1.need_pwd = book.need_pwd
                book1.save()
            return redirect('/user/mybook/')
        return render(request, 'edit_mybook.html', {'book': book, 'error': '有部分信息未填写！！！'})
    return render(request, 'edit_mybook.html', {'book': book})


@login_required
def search_book(request):
    flag = False  # flag用来控制模板的渲染
    # 获取当前用户
    pk = request.user.pk
    user = User.objects.filter(pk=pk)[0]
    if request.method == 'POST':
        flag = True
        search_book = request.POST.get('search_book')
        search_book_list = WB.objects.filter(
            title__icontains=search_book, is_public=True)
        return render(request, 'search_book.html', {'search_book_list': search_book_list, 'flag': flag})
    return render(request, 'search_book.html', {'flag': flag})


@login_required
def collect_mybook(request):
    # 获取当前用户
    pk = request.user.pk
    user = User.objects.filter(pk=pk)[0]
    # 查找当前单词本
    pk = request.GET.get('pk')
    book = WB.objects.get(pk=pk)
    # 将单词本拷贝到用户的单词本
    # 这里不设置pk等于原pk，如果设置会导致多个用户对该单词本具有修改权限
    book1 = UserBooks(title=book.title+'(收藏)', pub_date=book.pub_date,
                      is_public=False, password=book.password, need_pwd=False)
    book1.save()
    book1.master.add(user)
    return redirect('/user/mybook/')


@login_required
def verifypwd(request):
    # 获取当前用户
    pk = request.user.pk
    user = User.objects.filter(pk=pk)[0]
    # 查找当前单词本
    pk = request.GET.get('pk')
    book = WB.objects.get(pk=pk)
    if request.method == 'POST':
        password = request.POST.get('password')
        if password == book.password:
            # 将单词本拷贝到用户的单词本
            book1 = UserBooks(title=book.title+'(收藏)', pub_date=book.pub_date,
                              is_public=False, password=book.password, need_pwd=False)
            book1.save()
            book1.master.add(user)
            return redirect('/user/mybook/')
        else:
            error = '密码有误，请重新输入'
            return render(request, 'verifypwd.html', {'book': book, 'error': error})
    return render(request, 'verifypwd.html', {'book': book})


@login_required
def memorize(request):

    sql = 'select word_id,word_value,zh_meaning,sentence,phonetic from Word_word'
    sql1 = 'select word_id,word_notes from User_userwordnotes'
    sql2 = 'select word_id from User_userwordmemorize'
    params = {'status': 1}
    cursor = connections['default'].cursor()
    cursor.execute(sql, params)
    desc = cursor.description
    object_list = [
        dict(zip([col[0] for col in desc], row))
        for row in cursor.fetchall()
    ]
    cursor.close()
    current_page = request.GET.get('page')
    worddic = object_list

    cursor1 = connections['default'].cursor()
    cursor1.execute(sql1, params)
    desc1 = cursor1.description
    object_list1 = [
        dict(zip([col[0] for col in desc1], row))
        for row in cursor1.fetchall()
    ]
    cursor1.close()
    wordnotes = object_list1

    cursor2 = connections['default'].cursor()
    cursor2.execute(sql1, params)
    desc2 = cursor2.description
    object_list2 = [
        dict(zip([col[0] for col in desc2], row))
        for row in cursor1.fetchall()
    ]
    cursor2.close()
    wordid = object_list2

    for dic in worddic:
        for dic1 in wordnotes:
            if(dic['word_id'] == int(dic1['word_id'])):
                dic['word_notes'] = dic1['word_notes']
    # print(wordnotes)
   # print(worddic)
    # current_page=UserWordMemorize.objects.filter(id=1)[0].word_id
    print(UserWordMemorize.objects.filter(id=1)[0].word_id)
    paginator = Paginator(worddic, 1)
    try:
        posts = paginator.page(current_page)
    except PageNotAnInteger as e:
        posts = paginator.page(1)
    except EmptyPage as e:
        posts = paginator.page(1)
    pk = current_page  # 获取当前单词id
    UserWordMemorize.objects.filter(id=1).update(word_id=pk)
    if request.method == 'POST':

        if request.POST.get('user_wordnotes').isdigit():
            notes = request.POST.get('user_wordnotes')
            UserWordNotes.objects.filter(word_id=pk).update(
                word_notes=notes)  # 根据id在个人信息中找到用户信息
        return redirect('/user/memorize/?page='+str(current_page))

    return render(request, 'memorize.html', {'posts': posts})


@login_required
def takenotes(request):
    sql = 'select word_id,word_value,zh_meaning,phonetic from Word_word'
    sql1 = 'select word_id,word_notes from User_userwordnotes'

    params = {'status': 1}
    cursor = connections['default'].cursor()
    cursor.execute(sql, params)
    desc = cursor.description
    object_list = [
        dict(zip([col[0] for col in desc], row))
        for row in cursor.fetchall()
    ]
    cursor.close()
    current_page = request.GET.get('page')
    worddic = object_list

    cursor1 = connections['default'].cursor()
    cursor1.execute(sql1, params)
    desc1 = cursor1.description
    object_list1 = [
        dict(zip([col[0] for col in desc1], row))
        for row in cursor1.fetchall()
    ]
    cursor1.close()
    wordnotes = object_list1

    for dic in worddic:
        for dic1 in wordnotes:
            if(dic['word_id'] == int(dic1['word_id'])):
                dic['word_notes'] = dic1['word_notes']

    # print(wordnotes)
    # print(worddic)
    paginator = Paginator(worddic, 5)
    try:
        posts = paginator.page(current_page)
    except PageNotAnInteger as e:
        posts = paginator.page(1)
    except EmptyPage as e:
        posts = paginator.page(1)

    return render(request, 'wordnotes.html', {'posts': posts})
